package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Arriveschool;
import com.example.springboot.entity.Classes;
import com.example.springboot.entity.User;
import com.example.springboot.service.IArriveschoolService;
import com.example.springboot.service.IUserService;
import com.example.springboot.service.impl.ClassesServiceImpl;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/arriveschool")
public class ArriveschoolController {

    private final String now = DateUtil.now();
    @Resource
    IUserService userService;
    @Resource
    private IArriveschoolService arriveschoolService;
    @Autowired
    private ClassesServiceImpl classesServiceImpl;

    @PostMapping("/pay/{id}")
    public Result pay(@PathVariable("id") Integer id) {
        Arriveschool arriveschool = arriveschoolService.getById(id);
        if (arriveschool.getPaymentStatus().equals("已支付")) {
            return Result.error("400", "已支付，不能重复支付");
        }
        arriveschool.setPaymentStatus("已支付");
        arriveschoolService.updateById(arriveschool);
        return Result.success();
    }

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Arriveschool arriveschool) {
        if (arriveschool.getId() == null) {
            Integer userid = arriveschool.getUserid();
            QueryWrapper<Arriveschool> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid", userid);
            final Arriveschool one = arriveschoolService.getOne(queryWrapper);
            if (null != one) {
                return Result.error("400", "只能提交一次，不能重复提交");
            }
            arriveschool.setPaymentStatus("未支付");
        }
        arriveschoolService.saveOrUpdate(arriveschool);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        arriveschoolService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        arriveschoolService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(arriveschoolService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(arriveschoolService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer userid,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Arriveschool> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (userid != -1) {
            queryWrapper.eq("userid", userid);
        }
        return Result.success(arriveschoolService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/byTeacherPage")
    public Result findByTeacherPage(@RequestParam(defaultValue = "") String name,
                                    @RequestParam Integer userid,
                                    @RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize) {
        QueryWrapper<Arriveschool> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        User byId = userService.getById(userid);
        if (byId != null && byId.getRole().equals("ROLE_TEACHER")) {
            List<Classes> list = classesServiceImpl.list(new LambdaQueryWrapper<Classes>().eq(Classes::getTeacherId, userid));
            if (list.isEmpty()) return Result.success(new Page<>());
            queryWrapper.in("classid", list.stream().map(Classes::getId).collect(Collectors.toList()));
        }


        return Result.success(arriveschoolService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/agree")
    public Result agree(@RequestParam Integer id) {
        QueryWrapper<Arriveschool> queryWrapper = new QueryWrapper<>();
        Arriveschool byId = arriveschoolService.getById(id);
        if (byId != null) {
            byId.setStatus("审核通过");
            arriveschoolService.updateById(byId);
            return Result.success("审核通过");
        } else {
            return Result.error("400", "不存在数据，无法审核");
        }
    }

    @GetMapping("/reject")
    public Result reject(@RequestParam Integer id) {
        QueryWrapper<Arriveschool> queryWrapper = new QueryWrapper<>();
        Arriveschool byId = arriveschoolService.getById(id);
        if (byId != null) {
            byId.setStatus("审核拒绝");
            arriveschoolService.updateById(byId);
            return Result.success("审核拒绝");
        } else {
            return Result.error("400", "不存在数据，无法审核");
        }
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Arriveschool> list = arriveschoolService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Arriveschool信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     *
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Arriveschool> list = reader.readAll(Arriveschool.class);

        arriveschoolService.saveBatch(list);
        return Result.success();
    }

    private User getUser() {
        return TokenUtils.getCurrentUser();
    }

}

